#include "curltool.h"
#include <string>
#include <iostream>
#include <list>
#include <curl/curl.h>
#include <QMutexLocker>
#include <QDebug>

CurlTool* CurlTool::m_curltool = nullptr;
QMutex* CurlTool::m_mutex;

CurlTool::CurlTool()
{
    qDebug() << "initt";

}
CurlTool* CurlTool::getInstance(){
    if(!m_curltool){
        QMutexLocker locker(m_mutex);
        if(!m_curltool){
            m_curltool = new CurlTool();
        }
    }
    return m_curltool;
}

curl_slist * CurlTool::setBaseInfo( curl_slist *tempHeaders){
    tempHeaders = curl_slist_append(tempHeaders, "Accept: application/json");
    tempHeaders = curl_slist_append(tempHeaders, "X-UBT-AppId: 300000014");
    tempHeaders = curl_slist_append(tempHeaders, "X-UBT-DeviceId:11111111");
    tempHeaders = curl_slist_append(tempHeaders, "X-UBT-Sign: \"f\"");
    tempHeaders = curl_slist_append(tempHeaders, "token: ");
    tempHeaders = curl_slist_append(tempHeaders, "Content-Type:application/json ");

    return tempHeaders;
}

static  size_t  curlSaveResponseToStdString(void *buffer, size_t size, size_t nmemb, std::string *lpVoid) {
    std::string* str = dynamic_cast<std::string*>((std::string *)lpVoid);
        if (NULL == str || NULL == buffer)
        {
            return -1;
        }
        char* pData = (char*)buffer;
        str->append(pData, size * nmemb);
        qDebug()  << "receive" << QString::fromUtf8(str->data());
        return nmemb;
}

std::string CurlTool::post(const char *url, const char *data, CURLcode *code){
    std::string response;

    // 初始化 curl
    CURL *curl = curl_easy_init();

    if (curl) {
        // Headers
        struct curl_slist *tempHeaders = NULL;
        tempHeaders =  setBaseInfo(tempHeaders);
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, tempHeaders);
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&response);
        curl_easy_setopt(curl,CURLOPT_POST, 1); // POST 请求
        curl_easy_setopt(curl,CURLOPT_POSTFIELDS, data); // POST 参数
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlSaveResponseToStdString);
        qDebug()<<"post data:      " << data;
        CURLcode temp = curl_easy_perform(curl);
        if(temp != CURLE_OK){
            qDebug() << "post fail";
            curl_slist_free_all(tempHeaders);
            curl_easy_cleanup(curl);
        }

        if (code != NULL) {
            *code = temp;
        }

        curl_slist_free_all(tempHeaders); /* free the header list */
    } else {
        if (code != NULL) {
            *code = CURLE_FAILED_INIT;
        }
    }

    // 释放 curl 资源
    curl_easy_cleanup(curl);

    return response;


}

CurlTool::~CurlTool(){

}


